//
//  UMoneyTextField.m
//  UPay
//
//  Created by Hero on 2023/10/28.
//  Copyright © 2023 SiMai. All rights reserved.
//

#import "UMoneyTextField.h"

@implementation UMoneyTextField


- (instancetype)init

{
    
    if(self= [super init]) {
        
        [self addRules];
        self.textAlignment = NSTextAlignmentRight;

    }
    
    return self;
    
}

- (instancetype)initWithFrame:(CGRect)frame

{
    
    self= [super initWithFrame:frame];
    
    if(self) {
        
        [self addRules];
    }
    
    return self;
    
}

- (void)addRules

{
    
    [self addTarget:self action:@selector(checkInput) forControlEvents:UIControlEventEditingChanged];
    
    self.keyboardType=UIKeyboardTypeDecimalPad;
    
}

- (void)checkInput

{
    
    NSString * string = [self.text stringByReplacingOccurrencesOfString:@"," withString:@""];
    
    if([string hasPrefix:@"00"]) { //不能已00开头
        
        string = [string substringToIndex:1];
        
    }
    
    if([string hasPrefix:@"."]) { //不能以小数点开头
        
        string = [string substringToIndex:0];
        
    }
    
    NSRange range = [string rangeOfString:@"."];
    
    if(range.location!=NSNotFound) {
        
        //不能输入多个小数点
        
        if([[string substringFromIndex:range.location+1]rangeOfString:@"."].location!=NSNotFound) {
            
            string = [string substringToIndex:string.length-1];
            
        }
        
        //最多输入两位小数
        
        if(string.length>= range.location+ range.length+3) {
            
            string = [string substringToIndex:range.location+3];
            
        }
        
    }else if(string.length>=11) { //金额小数点前不能超过九位
        
        string = [string substringToIndex:11];
        
    }
    
    self.text = string;
    
//    if ([string hasSuffix:@"."]) {
//        self.text  = [NSString stringWithFormat:@"%@.",[XJTool formatterMoney:string]];
//    }else {
//        self.text  = [XJTool formatterMoney:string];
//    }
//    
}


@end
